<template>
  <div class="app-container">
    <div class="filter-container">
      <!-- 名字 -->
      <el-input v-model="listQuery.personName" clearable :placeholder="$t('common.name')" style="width: 200px;" class="filter-item" @keyup.enter.native="handleFilter" />
      <!-- 卡号 -->
      <el-input
        v-model="listQuery.cardNo"
        clearable
        :placeholder="$t('produce.cardNo')"
        style="width: 200px;"
        class="filter-item"
        @keyup.enter.native="handleFilter"
      />
      <!-- 站号 -->
      <!-- <el-input
        v-model="listQuery.stationNumber"
        clearable
        :placeholder="$t('produce.stationNumber')"
        style="width: 200px;"
        class="filter-item"
        @keyup.enter.native="handleFilter"
      /> -->
      <!-- 搜索按钮 -->
      <el-button
        v-waves
        class="filter-item"
        style="margin-left: 10px;"
        type="primary"
        icon="el-icon-search"
        @click="handleFilter"
      >
        {{ $t('common.search') }}
      </el-button>
      <!-- 新建按钮 -->
      <el-button
        class="filter-item"
        style="margin-left: 10px;"
        type="primary"
        icon="el-icon-plus"
        @click="handleCreate"
      >
        {{ $t('common.creatNew') }}
      </el-button>
      <!-- 重置按钮 -->
      <el-button v-waves class="filter-item" type="primary" icon="el-icon-refresh" @click="handleReset">
        {{ $t('common.reset') }}
      </el-button>
      <!-- 从工厂服务器下载数据 -->
      <el-button
        v-if="editRight"
        v-waves
        class="filter-item"
        type="warning"
        icon="el-icon-download"
        @click="handleDownload"
      >
        {{ $t('produce.downloadUser') }}
      </el-button>
    </div>
    <!-- 表格 -->
    <el-table
      :key="tableKey"
      v-loading="listLoading"
      :data="list"
      :header-row-style="{ color: 'black' }"
      :header-cell-style="{ background: 'lightBlue' }"
      border
      fit
      highlight-current-row
      style="width: 100%;"
    >
      <!-- 名字 -->
      <el-table-column :label="$t('common.name')" align="center">
        <template slot-scope="{row}">
          <span>{{ row.personName }}</span>
        </template>
      </el-table-column>
      <!-- 卡号 -->
      <el-table-column :label="$t('produce.cardNo')" prop="id" align="center">
        <template slot-scope="{row}">
          <span>{{ row.cardNo }}</span>
        </template>
      </el-table-column>
      <!-- 部门 -->
      <el-table-column :label="$t('produce.apartment')" align="center">
        <template slot-scope="{row}">
          <span>{{ row.apartment }}</span>
        </template>
      </el-table-column>
      <!-- 邮箱 -->
      <el-table-column :label="$t('produce.email')" align="center">
        <template slot-scope="{row}">
          <span>{{ row.email }}</span>
        </template>
      </el-table-column>
      <!-- 电话 -->
      <el-table-column :label="$t('produce.telephone')" align="center">
        <template slot-scope="{row}">
          <span>{{ row.telephone }}</span>
        </template>
      </el-table-column>
      <!-- 操作 -->
      <el-table-column :label="$t('common.operation')" align="center" class-name="small-padding fixed-width">
        <template slot-scope="{row,$index}">
          <!-- <el-button v-if="row.userId != 'administrator' && row.statusFlag != 'lock'" type="info" size="mini"
                        @click="handUpdateState('lock', row, $index)">
                        {{ $t('permission.lock') }}
                    </el-button>
                    <el-button v-if="row.userId != 'administrator' && row.statusFlag != 'unlock'" type="success"
                        size="mini" @click="handUpdateState('unlock', row, $index)">
                        {{ $t('permission.unlock') }}
                    </el-button> -->
          <el-button type="primary" size="mini" @click="handleUpdate(row, $index)">
            {{ $t('common.edit') }}
          </el-button>
          <el-button v-if="row.userId != 'administrator'" size="mini" type="danger" @click="handleDelete(row, $index)">
            {{ $t('common.delete') }}
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页 -->
    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="listQuery.page"
      :limit.sync="listQuery.limit"
      @pagination="getList"
    />
    <!-- 弹窗 -->
    <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible">
      <el-form
        ref="dataForm"
        :rules="rules"
        :model="temp"
        label-position="right"
        label-width="150px"
        style="display: flex;"
      >
        <div class="avatarBox" style="width: px;">
          <p style="color: #606266;font-weight: 700;margin-left:180px">{{ $t('produce.avatar') }}</p>
          <!-- 上传图片 -->
          <el-form-item>
            <el-upload
              action="#"
              list-type="picture-card"
              :auto-upload="false"
              :limit="1"
              :on-exceed="handleExceed"
              :file-list="fileList"
              :on-change="handleChange"
              :before-upload="beforeAvatarUpload"
            >
              <i class="el-icon-plus" />
            </el-upload>
          </el-form-item>
        </div>
        <div>
          <!-- 名字 -->
          <el-form-item :label="$t('common.name')">
            <el-input v-model="temp.personName" :placeholder="$t('common.name')" />
          </el-form-item>
          <!-- 卡号 -->
          <el-form-item :label="$t('produce.cardNo')" prop="cardNo">
            <el-input v-model="temp.cardNo" :placeholder="$t('produce.cardNo')" />
          </el-form-item>
          <!-- 部门 -->
          <el-form-item :label="$t('produce.apartment')">
            <el-input v-model="temp.apartment" :placeholder="$t('produce.apartment')" />
          </el-form-item>
          <!-- 邮箱 -->
          <el-form-item :label="$t('produce.email')">
            <el-input v-model="temp.email" :placeholder="$t('produce.email')" />
          </el-form-item>
          <!-- 电话 -->
          <el-form-item :label="$t('produce.telephone')">
            <el-input v-model="temp.telephone" :placeholder="$t('produce.telephone')" />
          </el-form-item>
          <!-- 权限 -->
          <el-form-item :label="$t('produce.stationAccess')">
            <el-tree
              ref="tree"
              :data="treeData"
              show-checkbox
              node-key="processNumber"
              highlight-current
              :props="defaultProps"
              @node-expand="handleTree"
            />
          </el-form-item>
        </div>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">
          {{ $t('common.cancel') }}
        </el-button>
        <el-button type="primary" @click="dialogStatus === 'create' ? createData() : updateData()">
          {{ $t('common.ok') }}
        </el-button>
      </div>
    </el-dialog>

    <!-- <el-dialog :visible.sync="dialogPvVisible" title="Reading statistics">
            <el-table :data="pvData" border fit highlight-current-row style="width: 100%">
                <el-table-column prop="key" label="Channel" />
                <el-table-column prop="pv" label="Pv" />
            </el-table>
            <span slot="footer" class="dialog-footer">
                <el-button type="primary" @click="dialogPvVisible = false">Confirm</el-button>
            </span>
        </el-dialog> -->
  </div>
</template>

<script>
import { getProcessList } from '@/api/equipment'
import waves from '@/directive/waves' // waves directive
import Pagination from '@/components/Pagination' // secondary package based on el-pagination
import i18n from '@/lang'
import { getOperator, creatOperator, updateOperator, deleteOperator, dowloadUserFromMes } from '@/api/produce'

export default {
  name: 'ComplexTable',
  components: { Pagination },
  directives: { waves },
  filters: {
    statusFilter(status) {
      const statusMap = {
        published: 'success',
        draft: 'info',
        deleted: 'danger'
      }
      return statusMap[status]
    }
  },
  data() {
    return {
      treeData: [],
      defaultProps: {
        label: 'processName'
      },
      tableKey: 0,
      list: [],
      roles: [],
      total: 0,
      listLoading: true,
      listQuery: {
        personName: '',
        Page: 1,
        Limit: 20,
        state: 0,
        lineNumber: '',
        stationNumber: '',
        cardNo: '',
        personNumber: '',
        startTime: '2022-05-17 00:00:00',
        endTime: '',
        sort: '+sequence'
      },
      lineQuery: {
        page: 1,
        limit: 20
      },
      processList: {
        lineId: ''
      },
      showReviewer: false,
      temp: {
        operatorId: 2,
        cardNo: '',
        avatar: '',
        apartment: '',
        shift: 0,
        stationAccess: [],
        personName: '',
        telephone: '',
        email: ''
      },
      password2: '',
      // 存放上传文件的历史纪录
      fileList: [],
      dialogFormVisible: false,
      dialogStatus: '',
      textMap: {
        update: i18n.t('common.edit'),
        create: i18n.t('common.creatNew')
      },
      dialogPvVisible: false,
      pvData: [],
      rules: {
        cardNo: [{ required: true, message: i18n.t('msg.CAN_NOT_BE_NULL'), trigger: 'change' }]
      },
      downloadLoading: false
    }
  },
  created() {
    this.editRight = (this.$store.getters.roles === 'admin' || this.$store.getters.roles === 'administrator')
    // 获取线体
    this.listQuery.lineNumber = this.$store.getters.lineNumber
    this.getList()
    this.getProcessOptions()
    // console.log(this.listQuery.lineNumber)
  },
  methods: {
    handleTree(data, node) {
      // console.log(250, data, node)
    },
    // 获取线体清单
    getProcessOptions() {
      this.listLoading = true
      getProcessList(this.listQuery).then(res => {
        this.treeData = res.data.processes
        // console.log(this.treeData)
        this.listLoading = false
      })
    },
    // 上传图片
    beforeAvatarUpload(file) {
      console.log(file)
      const isPNG = file.type === 'image/png'
      const isLt2M = file.size / 1024 / 1024 < 2
      if (!isPNG) {
        this.$message.error('上传头像图片只能是 PNG 格式!')
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!')
      }
      return isPNG && isLt2M
    },
    // 超出限制时触发
    handleExceed(files, fileList) {
      this.$message.warning(`当前限制选择 3 个文件，本次选择了 ${files.length} 个文件，共选择了 ${files.length + fileList.length} 个文件`)
    },
    // 获取操作员清单
    getList() {
      this.listLoading = true
      getOperator(this.listQuery).then(response => {
        // console.log(response)
        this.list = response.data.operators
        this.total = response.data.total
        this.listLoading = false
      })
    },
    // 点击搜索时获取清单
    handleFilter() {
      this.listQuery.page = 1
      this.getList()
    },
    // 初始化创建信息
    resetTemp() {
      this.temp = {
        cardNo: '',
        avatar: '',
        apartment: '',
        shift: 0,
        stationAccess: [],
        personName: '',
        telephone: '',
        email: ''
      }
    },
    // 新建一个任务
    handleCreate() {
      this.resetTemp()
      this.dialogStatus = 'create'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
        this.$refs.tree.setCheckedNodes([])
      })
    },
    // 从服务器下载数据
    handleDownload() {
      this.$confirm(i18n.t('produce.downloadOrNot'), i18n.t('common.tip'), {
        confirmButtonText: i18n.t('common.confirm'),
        cancelButtonText: i18n.t('common.cancel'),
        type: 'warning'
      }).then(() => {
        this.listLoading = true
        dowloadUserFromMes(this.listQuery).then(response => {
          this.getList()
          this.$message({
            type: 'success',
            message: i18n.t('msg.DOWNLOAD_SUCCESS')
          })
          this.listLoading = false
        })
      })
    },
    // 上传图片时的函数
    handleChange(file, fileList) {
      console.log(file)
      this.temp.avatar = file.raw
      console.log(this.temp.avatar)
    },
    // 创建数据
    createData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          console.log(this.temp.avatar)
          const fd = new FormData()
          fd.append('avatar', this.temp.avatar)
          for (var key of fd) {
            console.log(key[0] + ', ' + key[1])
          }
          console.log(fd)
          this.temp.stationAccess = []
          this.$refs.tree.getCheckedKeys().forEach(e => {
            this.temp.stationAccess.push({ cardNo: this.temp.cardNo, lineNumber: this.listQuery.lineNumber, processNumber: e })
          })
          creatOperator(fd).then(response => {
            this.list.unshift(response.data)
            this.dialogFormVisible = false
            this.$notify({
              title: i18n.t('common.tip'),
              message: i18n.t('msg.CREAT_SUCCESS'),
              type: 'success',
              duration: 2000
            })
            this.getList()
          })
        }
      })
    },
    // 点击编辑按钮
    handleUpdate(row, $index) {
      this.temp = Object.assign({}, row) // copy obj
      this.dialogStatus = 'update'
      this.dialogFormVisible = true
      if (this.temp.avatar === '') {
        this.temp.avatar = ''
      }
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
        if (row.stationAccess === null || row.stationAccess === undefined) {
          this.$refs.tree.setCheckedNodes([])
        } else {
          this.$refs.tree.setCheckedNodes(row.stationAccess)
        }
      })
    },
    // 更新数据到数据库
    updateData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          this.temp.stationAccess = []
          this.$refs.tree.getCheckedKeys().forEach(e => {
            this.temp.stationAccess.push({ cardNo: this.temp.cardNo, lineNumber: this.listQuery.lineNumber, processNumber: e })
          })
          const tempData = Object.assign({}, this.temp)
          updateOperator(tempData).then(response => {
            const index = this.list.findIndex(v => v.operatorId === this.temp.operatorId)
            this.list.splice(index, 1, response.data)
            this.dialogFormVisible = false
            this.$notify({
              title: i18n.t('common.tip'),
              message: i18n.t('msg.UPDATE_SUCCESS'),
              type: 'success',
              duration: 2000
            })
          })
        }
      })
    },
    // 删除信息
    handleDelete(row, index) {
      this.$confirm(i18n.t('msg.DELET_ACCOUNT_CONFIRM'), i18n.t('common.warn'), {
        confirmButtonText: i18n.t('common.ok'),
        cancelButtonText: i18n.t('common.cancel'),
        type: 'warning'
      })
        .then(async() => {
          this.temp = Object.assign({}, row) // copy obj
          deleteOperator(this.temp).then(() => {
            this.$notify({
              title: i18n.t('common.tip'),
              message: i18n.t('msg.DELETE_SUCCESS'),
              type: 'success',
              duration: 2000
            })
            this.list.splice(index, 1)
            this.getList()
          })
        })
        .catch(err => { console.error(err) })
    },
    // 重置表单内容
    handleReset() {
      this.listQuery.personName = ''
      this.listQuery.cardNo = ''
      this.listQuery.stationNumber = ''
      this.listQuery.lineNumber = ''
    }
  }
}
</script>
<style lang="scss" scoped>
.avatar-uploader-icon {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}

.avatar-uploader .el-upload:hover {
  border-color: #409EFF;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 117px;
  height: 142px;
  line-height: 134px;
  text-align: center;
}

.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>
